/**
 * <pre>
 * Title: 		WithDrawController.java
 * Project: 	MSTS
 * Author:		pengfangliang
 * Create:	 	2012-6-28 下午03:27:46
 * Copyright: 	Copyright (c) 2012
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.msls.controller;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoResponseMsg;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.msls.vo.SessionMember;

/**
 * <pre>
 * 提现控制器
 * </pre>
 * 
 * @author shenshaopeng
 * @version 1.0, 2014-1-11
 */
@Controller
@RequestMapping("/draw")
public class WithDrawController extends BaseController {

    /**
     * 提现页
     */
    @RequestMapping(value = "/todraw")
    public String todraw(HttpServletRequest request, ModelMap map) {
        SessionMember session = getSessionMember(request);
        if (session == null) {
            return "/user/login/index.jsp";
        }
        UserInfo user = getSessionMember(request).getUser();
        UserInfo m = serviceFactory.getUserInfoService().getUserInfoById(user.getId());
        if (StringHelper.isEmpty(m.getTrustAccountId())) {
			return "redirect:/member/goregpnr.htm";
		}
        QueryCardInfoRequestMsg queryCardInfoRequestMsg = new QueryCardInfoRequestMsg();
        queryCardInfoRequestMsg.setUserName(m.getUserName());
        queryCardInfoRequestMsg.setUsrCustId(m.getTrustAccountId());
        queryCardInfoRequestMsg.setPartnerTransType(PartnerTransType.QueryCardInfo);
        queryCardInfoRequestMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        queryCardInfoRequestMsg.setBgRetUrl(service_notify_url);
        queryCardInfoRequestMsg.setRetUrl(page_return_url);
        QueryCardInfoResponseMsg queryCardInfoResponseMsg = (QueryCardInfoResponseMsg) serviceFactory.getProtFactory()
                .remoteTrans(queryCardInfoRequestMsg);

        map.put("isBindCard", queryCardInfoResponseMsg.getUsrCardInfolist() != null
                && queryCardInfoResponseMsg.getUsrCardInfolist().size() > 0 ? "1" : "0");
        Account account = serviceFactory.getAccountService().getAccount(session.getUser().getId());
        map.put("account", account);
        return "/page/account/withdraw.jsp";
    }

    /**
     * 提现
     * 
     * @param request
     * @param money
     * @param bankCardId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/draw", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<ResponseMessage> draw(HttpServletRequest request, String money, Long bankCardId)
            throws Exception {
        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        CashRequestMsg reqMsg = new CashRequestMsg();
        UserInfo m = getSessionMember(request).getUser();
        Account account = serviceFactory.getAccountService().getAccount(m.getId());
        BigDecimal availableBalance = (new BigDecimal(account.getBaseMoney()-account.getFreezeMoney())).divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP);
        if ((availableBalance.subtract(new BigDecimal(StringUtils.isEmpty(money) ? "0" : money)))
                .compareTo(new BigDecimal("2")) == -1) {
            result.setIsSuccess(false);
            result.setMessage("由于提现需要手续费2元，您最多提现:" + (availableBalance.doubleValue() - 2) + "元");
            result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            return result;
        }
        reqMsg.setUserId(m.getId());
        reqMsg.setTransAmt(money);
        reqMsg.setPageType("2");
        reqMsg.setPartnerTransType(PartnerTransType.Cash);
        reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        reqMsg.setBgRetUrl(service_notify_url);
        reqMsg.setRetUrl(page_return_url);
        ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
        result.setReturnValue(response);
        if (!validateObjectsNullOrEmpty(response)) {
            result.setMessage(response.getRespDesc());
            result.setCode(response.getRespCode());
            if (response.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC)) {
                result.setIsSuccess(true);
            } else {
                result.setIsSuccess(false);

            }
        } else {
            result.setMessage("请求出错，请重试！");
            result.setIsSuccess(false);
            result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            logger.info("提现请求出错，返回null");
        }
        refreshSessionMember(request);
        return result;
    }
}
